package cn.zx.service.impl;

import cn.zx.mapper.UserMapper;
import cn.zx.po.User;
import cn.zx.service.UserService;
import cn.zx.utils.MailUtils;
import cn.zx.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户模块的业务逻辑层的实现接口类
 * Created by zzz on 2016/9/3.
 */
@Service("userServiceImpl")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 检查该用户，是否已存在
     * @return
     */
    public User findByUsername(String username) throws Exception {
        User user = userMapper.findByUsername(username);
        return user;
    }

    /**
     * 用户注册，保存用户信息
     * @param user
     * @throws Exception
     */
    public void saveUserInfo(User user) throws Exception {
        //保存状态码，0代表用户未激活，1代表用户已激活
        user.setState(0);
        //保存注册码
        String code = UUIDUtils.getUUID() + UUIDUtils.getUUID();
        user.setCode(code);
        MailUtils.sendMail(user.getEmail(),code);
        //保存用户信息到数据库
        userMapper.saveUserInfo(user);
    }

    /**
     * 激活用户
     * @param code
     * @return
     */
    public User findByCode(String code)throws Exception {
        User existUser =  userMapper.findByCode(code);
        return existUser;
    }

    /**
     * 修改数据库中保存的用户信息
     * @param existUser
     * @throws Exception
     */
    public void updateUserInfo(User existUser) throws Exception {
        userMapper.updateUserInfo(existUser);
    }

    /**
     * 查找数据库，用户登录
     * @param user
     * @return
     * @throws Exception
     */
    public User login(User user) throws Exception {
        User existUser = userMapper.login(user);
        return existUser;
    }
}
